﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using System.Text.RegularExpressions;

namespace Conusic.Model
{
    public static class LastFm
    {
        private const int HintMaxLength = 128;
        /*"artist": "Ленинград",
                   "id": "6-1255816",
                   "image": "2125016.jpg",
                   "reach": 153342,
                   "resid": 1255816,
                   "restype": 6,*/
        private static readonly Regex regex = new Regex(
             "\"artist\": \"([^\"]*)\"[^}]*?\"image\": \"([^\"]*)\"[^}]*?\"r" +
             "estype\": (6|8|9)",
            RegexOptions.CultureInvariant
            | RegexOptions.IgnorePatternWhitespace
            | RegexOptions.Compiled
            );

        public enum HintType
        {
            Artist = 6,
            Album = 8,
            Compositon = 9
        }
        public class Hint
        {
            public HintType HintCategory { get; private set; }
            public string Image { get; private set; }
            public string Name { get; private set; }

            public Hint(HintType type, string image, string name)
            {
                this.HintCategory = type;
                this.Image = image;
                this.Name = name;
            }

            public override string ToString()
            {
                return String.Format("{0} {1} {2}", HintCategory, Image, Name);
            }
        }

        public static List<Hint> RequestHints(string query)
        {
            if (query == null) throw new ArgumentNullException("query");
            if (query.Length > HintMaxLength) throw new ArgumentException("query");

            var page = SimpleHttp.RequestPage(
                String.Format(@"http://last.fm/search/autocomplete?q={0}&force=1",
                System.Web.HttpUtility.UrlEncode(query))
                );

            var match = regex.Match(page);

            if (!match.Success)
                return null;

            List<Hint> result = new List<Hint>();
            while (match.Success)
            {
                result.Add(new Hint(
                    (HintType)int.Parse(match.Groups[3].ToString()),
                    match.Groups[1].ToString(),
                    match.Groups[2].ToString()
                ));
                match = match.NextMatch();
            }
            return result;
        }
    }
}
